
import fs from 'fs'
import path from 'path'

function promiseify(func: Function) {
  // 返回一个新的函数
  return function (...arg: Array<any>) {
    return new Promise((resolve, reject) => {
      // 拼装参数
      arg.push(function (err: any, res: any) {
        if (err) {
          return reject(err)
        }
        return resolve(res)
      })
      return func.apply(func, arg) // 调用组装好的函数
    })
  }
}



// 读取文件目录
async function getCurrentDir(filePath: string, deepDeconstruction = true) {
  const readdirSync = promiseify(fs.readdir)
  const fileTreeList: Array<any> = []
  const directoryLsit: Array<string> = []
  try {
    const fileArr: any = await readdirSync(filePath)
    // 得到当前文件所在路径的文件列表 => fileArr 一个数组
    // 循环遍历 files生成文件树
    for (let i = 0; i < fileArr.length; i++) {
      let item = fileArr[i]
      if (['node_modules', 'dist'].includes(item)) {
        // 跳过本次迭代
        continue
      }
      const curItemAbsPath = path.join(filePath, item)
      const statSync = promiseify(fs.stat)
      const stats: any = await statSync(curItemAbsPath)
      if (stats.isDirectory()) {
        // 当前item 为一个目录
        if (deepDeconstruction) {
          // 需要深层解构子目录
          const childFileArr: Array<string> = await getCurrentDir(curItemAbsPath)
          fileTreeList.push(childFileArr)
        } else {
          // 不需要深层解构子目录, 只获取目录名
          directoryLsit.push(item)
        }
      } else {
        // 当前item为一个文件
        fileTreeList.push(curItemAbsPath)
      }
    }
  } catch (err) {
    console.log('err:', err)
  } finally {
    return deepDeconstruction ? fileTreeList : directoryLsit
  }
}

// 前端主文件目录
type FrontendMainFileCatalogues = {
  CurrentFrontendPath: string;
  Src: string;
  Views: string;

}

function getForntendPath(): FrontendMainFileCatalogues {
  // 获取当前文件的绝对路径
  const fileAbsPath = path.resolve()
  const frontendPath = path.join(fileAbsPath, '..', './vue-typescript-admin-template') // 前端文件路径
  const frontendSrcPath = path.join(frontendPath, './src')
  const frontendSrcViewsPath = path.join(frontendSrcPath, './views')

  return <FrontendMainFileCatalogues>{
    CurrentFrontendPath: frontendPath,
    Src: frontendSrcPath,
    Views: frontendSrcViewsPath,
  }
}

async function main() {
  try {
    // 获取当前文件的绝对路径
    // const fileAbsPath = path.resolve()
    const fileAbsPath = getForntendPath().Views
    const directoryLsit = await getCurrentDir(fileAbsPath, true)
    console.log('fileAbsPath:', fileAbsPath);
    return directoryLsit
  } catch (err) {
    console.log('err:', err);
  }
}

export { main as getCurrentDir }